package com.lab.utils.imageupload.imp;

import android.util.Log;

import com.cuitrip.apiservice.CommonBusiness;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.ThreadUtil;
import com.lab.utils.imageupload.model.QiniuTokenObject;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONObject;

import java.util.Calendar;

/**
 * 七牛服务
 * Created by ak on 5/5/16.
 */
public enum QiniuService {

    INSTANCE;

    private UploadManager mUploadManager;
    private QiniuTokenObject qiniuTokenObject;
    private boolean isCancelled;

    public static String getObjectName(String uid) {
        String fileExtName = ".jpg";
        return new StringBuilder(uid).append("_").append(Calendar.getInstance().getTimeInMillis()).append(fileExtName).toString();
    }

    public QiniuService getInstance() {
        return INSTANCE;
    }

    public void initClient(QiniuTokenObject qiniuTokenObject) {
        this.mUploadManager = new UploadManager();
        this.qiniuTokenObject = qiniuTokenObject;
        this.isCancelled = false;
    }

    public void asyncPutImage(String key, String localFile, final UploadCallback uploadCallback) {
        mUploadManager.put(localFile, key, qiniuTokenObject.getToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(final String key, final ResponseInfo info, JSONObject res) {
                        //  res 包含hash、key等信息，具体字段取决于上传策略的设置。
                        Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                        if (info.isOK()) {
                            ThreadUtil.MAIN_THREAD_HANDLER.post(new Runnable() {
                                @Override
                                public void run() {
                                    uploadCallback.onSuccess(getReturnUrl(key));
                                }
                            });
                        } else {
                            ThreadUtil.MAIN_THREAD_HANDLER.post(new Runnable() {
                                @Override
                                public void run() {
                                    uploadCallback.onFailure(info.error);
                                }
                            });
                        }
                    }
                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(final String key, final double percent) {
                                Log.i("qiniu", key + ": " + percent);
                                ThreadUtil.MAIN_THREAD_HANDLER.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadCallback.onProgress((int) (percent * 100));
                                    }
                                });
                            }
                        }, new UpCancellationSignal() {
                    @Override
                    public boolean isCancelled() {
                        return isCancelled;
                    }
                }));
    }

    public void cancelUpload() {
        this.isCancelled = true;
    }

    public void requestTokenObject(final RequestQiniuTokenCallback requestQiniuTokenCallback) {
        ApiProxy apiProxy = new ApiProxy(new IProxyCallback() {
            @Override
            public boolean onProxyResult(ProxyResult<?> result) {
                CtApiResponse response = (CtApiResponse) result.getData();
                if (response.isResponseNormal()) {
                    if (response.result instanceof QiniuTokenObject) {
                        QiniuTokenObject ossTokenObject = (QiniuTokenObject) response.result;
                        initClient(ossTokenObject);
                        requestQiniuTokenCallback.onSuccess(ossTokenObject);
                    }
                } else {
                    requestQiniuTokenCallback.onFailed(response.msg);

                }
                return false;
            }
        });
        CommonBusiness.getQiniuOssToken(apiProxy);
    }

    private String getReturnUrl(String objectKey) {
        return String.format("%s%s", qiniuTokenObject.getUrlPrefix(), objectKey);
    }

    public interface RequestQiniuTokenCallback {
        public void onSuccess(QiniuTokenObject qiniuTokenObject);

        public void onFailed(String errorMessage);
    }

    public interface UploadProgressCallback {
        public void onProgress(int progress);
    }

    public interface UploadCallback extends UploadProgressCallback {

        public void onFailure(String errorMessage);

        public void onSuccess(String url);

    }

}
